package com.example.kotlindemo.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlindemo.R
import com.example.kotlindemo.data.Task


class CompletedTaskAdapter(private val onTaskClicked: (Task) -> Unit) :
    ListAdapter<Task, CompletedTaskAdapter.CompletedTaskViewHolder>(TaskDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CompletedTaskViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_completed_task, parent, false)
        return CompletedTaskViewHolder(view, onTaskClicked)
    }

    override fun onBindViewHolder(holder: CompletedTaskViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class CompletedTaskViewHolder(itemView: View, private val onTaskClicked: (Task) -> Unit) :
        RecyclerView.ViewHolder(itemView) {

        // 使用 findViewById 获取视图
        private val taskNameTextView: TextView = itemView.findViewById(R.id.tvTaskNameCompleted)
        private val checkmarkImageView: ImageView = itemView.findViewById(R.id.ivCheckmarkCompleted)
        private var currentTask: Task? = null

        init {
            // 设置点击监听器，将事件通过回调传递出去
            checkmarkImageView.setOnClickListener {
                currentTask?.let { onTaskClicked(it) }
            }
        }

        fun bind(task: Task) {
            currentTask = task
            taskNameTextView.text = task.name
        }
    }
}